#include <stdlib.h>
#include <string.h>
#include "tab_sym.h"
#include "declarator_list.h"

struct table_symbole * tab_symb_vide(struct table_symbole *parent, int portee){
  struct table_symbole *tab = malloc(sizeof(struct table_symbole));
  tab->parent = parent;
  tab->portee = portee;
  tab->nb_symb = 0;
  tab->offset_min = 0;
  return tab;
}

void ajouter_var(struct table_symbole* tab, struct declarator* declarator){
  tab->symb[tab->nb_symb]->decl = declarator ;
  tab->nb_symb ++;
  if (declarator->mode == 1){
    tab->offset_min += 4;
  }

  else  if(declarator->mode == 2){
    struct taille *tmp = declarator->taille;
    int total = 1;
    while(tmp->next != NULL){    
      total *= 4*tmp->taille;
      tmp = tmp->next;
    } 
   tab->offset_min += total;
  }
  tab->symb[tab->nb_symb]->offset = tab->offset_min;  
}


void ajouter_func(struct table_symbole* tab, struct declarator *declarator){
  tab->symb[tab->nb_symb]->decl = declarator;
  tab->nb_symb ++;
  	}

int get_offset(struct table_symbole* tab, char *name){
  int i=0;
  while (strcmp(tab->symb[i]->decl->id, name) != 0 && i < tab->nb_symb)
    i++;
  if (strcmp(tab->symb[i]->decl->id, name) == 0){
    if(tab->portee == 10)
      return -tab->symb[i]->offset;
    else if (tab->portee == 11)
      return -tab->symb[i]->offset;
    else 
       return tab->symb[i]->offset;
  }
  else
    {
      if(tab->parent != NULL)
	return get_offset(tab->parent, name);
      else 
	return 0; //correspond à la sauvegarde de l'ebp donc on peut s'en servir pour la gestion d'erreur
    }
}


int get_type(struct table_symbole* tab, char *name){
  int i=0;
  while (strcmp(tab->symb[i]->decl->id, name) != 0 && i < tab->nb_symb)
    i++;
  if (strcmp(tab->symb[i]->decl->id, name) == 0){
      return tab->symb[i]->decl->type;
  }
  else
    {
      if(tab->parent != NULL)
	return get_type(tab->parent, name);
      else 
	return -1;
    }
}
    
